package com.tte.common.utils.file.impl;

import com.jcraft.jsch.*;
import com.tte.common.utils.file.FileTransferUtils;

import java.io.*;
import java.util.*;

public class SFTPUtil implements FileTransferUtils {
	private String temp = ".";
	Session sshSession = null;
	ChannelSftp ftp = null;
	/**
	 * Ftp服务器
	 */
	private String server;
	/**
	 * 用户名
	 */
	private String uname;
	/**
	 * 密码
	 */
	private String password;
	/**
	 * 连接端口，默认21
	 */
	private int port = 22;

	public SFTPUtil() {

	}

	/**
	 * 连接FTP服务器
	 * 
	 * @param server
	 * @param uname
	 * @param password
	 * @return
	 * @throws Exception
	 */
	public ChannelSftp connectFTPServer(String server, long port, String uname,
										String password) {
		return connectFTPServer(server, Integer.valueOf(String.valueOf(port)),
				uname, password);
	}

	public ChannelSftp connectFTPServer(String server, int port, String uname,
			String password) {
		this.server = server;
		this.port = port;
		this.uname = uname;
		this.password = password;
		// 初始化并保存信息
		try {
			JSch jsch = new JSch();
			jsch.getSession(uname, server, port);
			sshSession = jsch.getSession(uname, server, port);
			sshSession.setPassword(password);
			Properties sshConfig = new Properties();
			sshConfig.put("StrictHostKeyChecking", "no");
			sshSession.setConfig(sshConfig);
			sshSession.connect();
			Channel channel = sshSession.openChannel("sftp");
			channel.connect();
			ftp = (ChannelSftp) channel;
		} catch (Exception e) {

			return null;
		}
		return ftp;
	}

	/**
	 * 上传文件到FTP根目录
	 * 
	 * @param localFile
	 * @param newName
	 * @throws Exception
	 */
	public void uploadFile(String localFile, String newName) throws Exception {
//		InputStream input = null;
//		SftpProgressMonitor sf = new MyProgressMonitor();
//		try {
//			File file = new File(localFile);
//			input = new FileInputStream(file);
//			ftp.put(input, newName, sf);
//
//		} catch (Exception e) {
//			e.printStackTrace();
//			throw new Exception("文件上传失败!");
//		} finally {
//			input.close();
//		}
	}

	public void uploadFile2(String localFile, String newName) throws Exception {
//		InputStream input = null;
//		SftpProgressMonitor sf = new MyProgressMonitor();
//		try {
//			File file = new File(localFile);
//			input = new FileInputStream(file);
//			ftp.put(input, newName, sf);
//
//		} catch (Exception e) {
//			throw new Exception("文件上传失败!");
//		} finally {
//			input.close();
//		}
	}

	public static final InputStream byte2Input(byte[] buf) {
		return new ByteArrayInputStream(buf);
	}

	public static final byte[] input2byte(InputStream inStream)
			throws IOException {
		ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
		byte[] buff = new byte[100];
		int rc = 0;
		while ((rc = inStream.read(buff, 0, 100)) > 0) {
			swapStream.write(buff, 0, rc);
		}
		byte[] in2b = swapStream.toByteArray();
		return in2b;
	}

	@Override
	public String getType() {
		return null;
	}

	@Override
	public boolean isConnect() {
		return false;
	}

	@Override
	public boolean checkParams() {
		return false;
	}

	@Override
	public String uploadFile(String localFile) throws Exception {
		return null;
	}

	/**
	 * 上传文件到FTP根目录
	 * 
	 * @param input
	 * @param newName
	 * @throws Exception
	 */
	public String uploadFile(InputStream input, String newName) throws Exception {
//		SftpProgressMonitor sf = new MyProgressMonitor();
//		try {
//			if (input != null) {
//
//				ftp.put(input, newName, sf);
//			}
//
//		} catch (Exception e) {
//			throw new Exception("文件上传失败!");
//		} finally {
//			if (input != null) {
//				input.close();
//			}
//		}
		return null;
	}

	@Override
	public String uploadFile(File file, String newName) throws Exception {
		return null;
	}

	@Override
	public InputStream downloadFile(String savePath) throws Exception {
		return null;
	}

	@Override
	public Byte[] downloadByte(String savePath) throws Exception {
		return new Byte[0];
	}

	/**
	 * 上传文件到指定的FTP路径下
	 * 
	 * @param localFile
	 * @param newName
	 * @param remoteFoldPath
	 * @throws Exception
	 */
	public void uploadFile(String localFile, String newName,
			String remoteFoldPath) throws Exception {
//		InputStream input = null;
//		SftpProgressMonitor sf = new MyProgressMonitor();
//		try {
//			createDirectorys(remoteFoldPath);
//			remoteFoldPath = remoteFoldPath.replace("\\", "/").trim();
//
//			if (remoteFoldPath.substring(0, 1).endsWith("/")) {
//				ftp.put(localFile, "."+remoteFoldPath+"/"+newName, sf);
//			} else {
//				ftp.put(localFile, "./"+remoteFoldPath+"/"+newName, sf);
//			}
//
//		} catch (Exception e) {
//			throw e;
//		} finally {
//			if (input != null) {
//				input.close();
//			}
//		}
	}


	/**
	 * 上传文件到指定的FTP路径下
	 * 
	 * @param input
	 * @param newName
	 * @param remoteFoldPath
	 * @throws Exception
	 */
	public void uploadFile(InputStream input, String newName,
			String remoteFoldPath) throws Exception {
//		SftpProgressMonitor sf = new MyProgressMonitor();
//		try {
//
//			if (input != null) {
//				remoteFoldPath = remoteFoldPath.replace("\\", "/").trim();
//				createDirectorys(remoteFoldPath);
//
//				if (remoteFoldPath.substring(0, 1).endsWith("/")) {
//					ftp.cd("."+remoteFoldPath);
//				} else {
//					ftp.cd("./"+remoteFoldPath);
//				}
//				ftp.put(input, newName, sf);
//			}
//
//		} catch (Exception e) {
//			throw new Exception("文件上传失败!");
//		} finally {
//			if (input != null) {
//				input.close();
//			}
//		}
	}

	/**
	 * 从FTP指定的路径下载文件
	 * 
	 * @param remotePath
	 * @param localPath
	 */
	public boolean downloadFile(String remotePath, String localPath) throws Exception {
		OutputStream output = null;
		try {
			File file = new File(localPath);
			if (!file.exists()) {
				file.createNewFile();
			}
			output = new FileOutputStream(file);

			try {
				
				remotePath = remotePath.replace("\\", "/").trim();
				createDirectorys(remotePath);
				if (remotePath.substring(0, 1).endsWith("/")) {
					ftp.get(temp + remotePath, output);
				} else {
					ftp.get(temp + "/" + remotePath, output);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}

		} catch (Exception e) {
			throw new Exception("文件下载失败!");
		} finally {
			if (output != null) {
				output.close();
			}
		}
		return true;

	}

	/**
	 * 从FTP指定的路径下载文件
	 * 
	 * @param remoteFilePath
	 * @return
	 * @throws Exception
	 */
	public InputStream downFile(String remoteFilePath) throws Exception {
		InputStream is = null;
		try {
			remoteFilePath = remoteFilePath.replace("////", "/").trim();
			remoteFilePath = remoteFilePath.replace("///", "/").trim();
			remoteFilePath = remoteFilePath.replace("//", "/").trim();			
			remoteFilePath = remoteFilePath.replace("\\", "/").trim();
			if (remoteFilePath.substring(0, 1).endsWith("/")) {
				is=ftp.get(temp +remoteFilePath);
			} else {
				is=ftp.get(temp + "/" +remoteFilePath);
				
			}
			
		} catch (Exception e) {
			is = null;
		//	throw new Exception("文件下载失败!");
		}finally{
			
		}
		
		return is;
	}

	

	/**
	 * 从FTP指定的路径下载txt
	 * 
	 * @param remoteFilePath
	 * @return
	 * @throws Exception
	 */
	public String downTxt(String remoteFilePath) {
		ByteArrayOutputStream output = null;
		InputStream inputStream = null;
		try {

			output = new ByteArrayOutputStream();

			inputStream = downFile(remoteFilePath);

			byte[] buffer = new byte[1024];
			int len;
			while ((len = inputStream.read(buffer)) > -1) {
				output.write(buffer, 0, len);
			}

			return output.toString("utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}
		return null;
	}

	public OutputStream downOutputStream(String remoteFilePath) {
		OutputStream output = null;
		try {

			output = new ByteArrayOutputStream();
			try {
				remoteFilePath = remoteFilePath.replace("\\", "/").trim();
				if (remoteFilePath.substring(0, 1).endsWith("/")) {
					remoteFilePath = temp + remoteFilePath;
				} else {
					remoteFilePath = temp + "/" + remoteFilePath;
				}

				ftp.get(remoteFilePath, output);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		return output;
	}

	/**
	 * 获取FTP服务器上指定路径下的文件列表
	 * 
	 * @param filePath
	 * @return
	 */
	public List<String> getFtpServerFileList(String filePath) throws Exception {

		List<String> nlist = new ArrayList<String>();
		// FTPListParseEngine engine = ftp.initiateListParsing(filePath);

		return getFTPServerFileList(nlist, filePath);
	}

	/**
	 * 获取FTP服务器上指定路径下的文件列表
	 * 
	 * @param path
	 * @return
	 * @throws Exception
	 */
	public List<String> getFileList(String path) throws Exception {
		List<String> nlist = new ArrayList<String>();

		return getFTPServerFileList(nlist, path);
	}

	/**
	 * 获得给定的目录下的文件列表
	 * */
	/*
	 * public FTPFile[] getFilesByPathname(String pathname){ try {
	 * ftp.changeWorkingDirectory(pathname); return ftp.mlistDir(pathname); }
	 * catch (IOException e) { // TODO Auto-generated catch block
	 * e.printStackTrace(); } return null; }
	 */

	/**
	 * 列出FTP服务器文件列表信息
	 * 
	 * @param nlist
	 * @param
	 * @return
	 */
	public List<String> getFTPServerFileList(List<String> nlist, String filePath) {
		if (filePath == null){
			return nlist;
		}

		try {
			filePath = filePath.replace("\\", "/").trim();
			if (filePath.substring(0, 1).endsWith("/")) {
				filePath = temp + filePath;
			} else {
				filePath = temp + "/" + filePath;
			}
			Vector v = ftp.ls(filePath);
			int i = 0;
			for (Object o : v) {
				  if(o instanceof com.jcraft.jsch.ChannelSftp.LsEntry){
						ChannelSftp.LsEntry s = (ChannelSftp.LsEntry) v.get(i);
						if(!s.getAttrs().isDir()){
							 nlist.add(s.getFilename());
						}
					 
				  }
			
				i++;
			}
		} catch (SftpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return nlist;
	}

	/*
	 * public void appendFile(String remote,InputStream inputStream){ try {
	 * 
	 * ftp.appendFile(remote, inputStream); } catch (IOException e) {
	 * e.printStackTrace(); } }
	 */

	/**
	 * 改变工作目录，如失败则创建文件夹
	 * 
	 * @param remoteFoldPath
	 */
	public void changeDirectory(String remoteFoldPath) {
		remoteFoldPath = remoteFoldPath.replace("\\", "/");
		StringTokenizer s = new StringTokenizer(remoteFoldPath, "/");
		String pathName = "";
		while (s.hasMoreElements()) {
			pathName = pathName + "/" + s.nextElement().toString();

			try {
				if (!isExistDir(pathName)) {
					ftp.mkdir(temp + pathName);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 删除文件
	 * */
	public void deleteFile(String pathname) {
		try {

			pathname = pathname.replace("\\", "/").trim();

			if (pathname.substring(0, 1).endsWith("/")) {
				ftp.rm(temp + pathname);
			} else {
				ftp.rm(temp + "/" + pathname);
			}

			// ftp.deleteFile(pathname);
		} catch (SftpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 移动文件 并改名
	 * */
	public void moveFile(String fromPathName, String toPathName) {
		try {

			fromPathName = fromPathName.replace("\\", "/").trim();
			toPathName = toPathName.replace("\\", "/").trim();

			if (fromPathName.substring(0, 1).endsWith("/")) {
				fromPathName = temp + fromPathName;
			} else {
				fromPathName = temp + "/" + fromPathName;
			}
			if (toPathName.substring(0, 1).endsWith("/")) {
				toPathName = temp + toPathName;
			} else {
				toPathName = temp + "/" + toPathName;
			}

			ftp.rename(fromPathName, toPathName);
		} catch (SftpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 将ftp目录跳到指定的目录，如果目录不存在则创建该目录，然后再跳转
	 * 
	 * @param pathName
	 * @author ZhengNL
	 * @date 2012-9-14
	 */
	public void changeWorkDir(String pathName) {
		changeDirectory(pathName);

	}

	/**
	 * 创建目录
	 * */
	public void createDirectory(String pathname) {
		changeDirectory(pathname);

	}

	/**
	 * 创建多级目录
	 * */
	public void createDirectorys(String pathname) {
		changeDirectory(pathname);

	}

	/**
	 * 判断文件夹是否存在，存在返回true，否则返回false
	 * 
	 * @param dir
	 *            如 /zzz/bbb/
	 * @return
	 * @author ZhengNL
	 * @date 2012-9-18
	 */
	public boolean isExistDir(String dir) {
		boolean res = false;
		try {
			if(dir.substring(0,1).equals("/")){
				ftp.ls(temp + dir);
			}else{
				ftp.ls(temp + "/"+dir);
			}
			
			res=true;
		} catch (Exception e) {
			res = false;

		}finally{
			
		}

		return res;
	}

	/**
	 * 检查文件是否存在
	 * 
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public boolean checkFileExist(String filePath) throws Exception {
		boolean flag = false;
		File file = new File(filePath);
		if (file.exists()) {
			flag = true;
		}
		return flag;
	}

	/**
	 * 获取文件名,不包括后缀
	 * 
	 * @param filePath
	 * @return
	 */
	public String getFileNamePrefix(String filePath) throws Exception {

		boolean flag = this.checkFileExist(filePath);
		if (flag) {
			File file = new File(filePath);
			String fileName = file.getName();
			String _fileName = fileName.substring(0, fileName.lastIndexOf("."));
			return _fileName;
		}
		return null;
	}

	/**
	 * 关闭FTP连接
	 * 
	 * @param ftp
	 * @throws Exception
	 */
	public void closeFTPClient(ChannelSftp ftp) throws Exception {

		try {
			if (ftp != null) {
				ftp.disconnect();
				ftp.exit();
			}
			

		} catch (Exception e) {
			throw new Exception("关闭FTP服务出错!");
		}
	}

	/**
	 * 关闭FTP连接
	 * 
	 * @throws Exception
	 */
	public void closeFTPClient() throws Exception {

		this.closeFTPClient(this.ftp);

	}

	
	public void setServer(String server) {
		this.server = server;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setPort(int port) {
		this.port = port;
	}

	
	public ChannelSftp getFtp() {
		return ftp;
	}

	public void setFtp(ChannelSftp ftp) {
		this.ftp = ftp;
	}

	public String getServer() {
		return server;
	}

	public String getUname() {
		return uname;
	}

	public String getPassword() {
		return password;
	}

	public int getPort() {
		return port;
	}

	/**
	 * 主方法(测试)
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		SFTPUtil ftpUtil = new SFTPUtil();// ftp://admin@127.0.0.1/100008121/100010068/2012/{307A876E-24A2-475F-99B3-2EA7B104F4BC}.xml
//		sftp  ftpadmin/ftpadmin@192.168.0.142
//		路径是/data/ftpdata/ftpadmin

		try {
			// System.out.println(DateUtil.getCurrentTimeDetailString());
			long ff = System.currentTimeMillis();
			// ftpUtil.connectFTPServer("192.168.0.125", 44, "sftpwz","sftpwz");
//			ftpUtil.connectFTPServer("192.168.0.142", 22, "ftpadmin","ftpadmin");
//			ftpUtil.uploadFile("C:\\Users\\TTE\\Pictures\\2.jpg","文件名1.jpg","test1/test/test");
			ftpUtil.connectFTPServer("192.168.0.142", 22, "ftpadmin","ftpadmin");
			InputStream inputStream = ftpUtil.downFile("/test1/428713489/439811875/20221027/1135/2233641903/93da159e-ddf5-44dd-a638-a589589df207.jpg");
			System.out.println(inputStream.toString());
			inputStream.close();
			ftpUtil.closeFTPClient();

			System.out.println(ff);
			/*
			Vector v = ftpUtil.getFtp().ls("./ddcs");
			int i = 0;
			for (Object o : v) {
				  if(o instanceof com.jcraft.jsch.ChannelSftp.LsEntry){
						LsEntry s = (LsEntry) v.get(i);
						if(!s.getAttrs().isDir()){
							System.out.print(s.getFilename());
							System.out.println(s.getAttrs().getSize());
						}
					 
				  }
			
				i++;
			}

			System.out.println(System.currentTimeMillis() - ff);*/

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				ftpUtil.closeFTPClient();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
